<template>
  <div class="upload-img">
    <!--
      此处由于我司上传文件特殊，此处上传逻辑请看上传后成功的钩子函数
      此处成功为伪成功，具体上传逻辑在 handleAvatarSuccess 函数
    -->
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      list-type="picture"
      :http-request="_handleRequest"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <div slot="tip" class="el-upload__tip">请选择需要上传的图片</div>
    </el-upload>
  </div>
</template>

<script>
import { getToken, uuid } from '@/utils/auth'

export default {
  props: {
    formData: {
      type: Object,
      default: null
    },
    editImg: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 上传图片路径
      imageUrl: ''
    }
  },
  mounted() {
    this.imageUrl = this.editImg
  },
  methods: {
    // 覆盖默认的上传行为，可以自定义上传的实现
    _handleRequest(file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log(file, '文件上传信息')
      const params = {
        file: file.file,
        msgId: uuid(),
        token: getToken()
      }

      this.$api.upload.put(params).then(res => {
        // 照片的回显
        this.imageUrl = res.file_info.url
        this.$emit('imageUrl', this.imageUrl)
        this.$message({
          message: this.formData.AddEdit === 'add' ? '上传图片成功' : '更新照片成功',
          type: 'success'
        })
        // console.log(res, 999)
      }).catch((err) => {
        this.$message.error('上传图片失败')
        console.log(err, '上传失败')
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.upload-img{
  // 上传图片框的样式
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px solid rgb(193, 188, 188);
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
